import os
import time
from datetime import datetime
import shutil
import asyncio
import sys

def calculate_time_difference(date_string):
    # 将给定的日期字符串转换为datetime对象
    given_date = datetime.strptime(date_string, '%Y%m%d')
    # 获取当前日期和时间
    current_date = datetime.now()
    # 计算时间差
    time_difference = current_date - given_date
    # 将时间差转换为秒数的时间差
    time_difference_seconds = time_difference.total_seconds()
    # 返回时间差的时间戳
    return time_difference_seconds

def is_folder_empty(folder_path):
    # 获取文件夹中的文件列表
    files = os.listdir(folder_path)
    # 判断文件夹是否为空
    if len(files) == 0:
        return True
    else:
        return False

def delete_files_by_creation_time(path, time_gap):
    # 获取当前时间戳
    current_time = time.time()
    # 计算指定天数之前的时间戳
    threshold_time = current_time - time_gap

    # 遍历指定路径下的所有文件和文件夹
    for root, dirs, files in os.walk(path):
        for file in files:
            file_path = os.path.join(root, file)
            # 获取文件的创建时间
            creation_time = os.path.getmtime(file_path)
            print(f"-----file ------creation_time : {creation_time},-------threshold_time:{threshold_time} , ----res: {creation_time < threshold_time}")
            # 如果文件的创建时间早于指定的阈值时间，则删除文件
            if creation_time < threshold_time:
                os.remove(file_path)
                print(f"Deleted file: {file_path}")

        for dir in dirs:
            dir_path = os.path.join(root, dir)
            if is_folder_empty(dir_path):
                shutil.rmtree(dir_path)
            else:
                # 获取文件夹的创建时间
                creation_time = os.path.getctime(dir_path)
                # 如果文件夹的创建时间早于指定的阈值时间，则删除文件夹及其内容
                if creation_time < threshold_time:
                    # os.rmdir(dir_path)
                    shutil.rmtree(dir_path)
                    print(f"Deleted directory: {dir_path}")

async def main():
    if len(sys.argv) < 2:
        print(f"------请设置要清除的目录-----")
    else:
        root_dir = sys.argv[1]
        deadline_date = sys.argv[2]
        print(f"-----------root_dir: {root_dir}, ---- dealine_date:{deadline_date}")
        # 示例用法：删除指定路径下创建时间早于30天的文件和文件夹
        time_gap = calculate_time_difference(deadline_date)
        print(f"-----------time_gap: {time_gap}")
        delete_files_by_creation_time(root_dir, time_gap)


if __name__ == '__main__':
    asyncio.run(main())